const cheerio  = require('cheerio')
const {getHtmlDeatil} = require('../util/getHtml')
/**
 * @name getCateTitle
 * @description 获取页面的分类信息
 *
 */
function getCateTitle ($){
    let result = []

    $('.top-nav').find('li').each((idx,item) =>{
        let obj = {}
        obj['cate_href'] = $($(item)[0]).find('a').attr('href')
        obj['cate_title'] = $($(item)[0]).find('a').text()
        // 存在说明当前是多节点
        if (typeof $($(item)[0]).attr('_t_nav') !== 'undefined') {
            obj['child'] = []

            let id = $($(item)[0]).attr('_t_nav')
            $('.nav-down').find('#'+id).find('li').each((idx,li) => {
                let childObj = {}
                childObj['cate_href'] = $($(li)[0]).find('a').attr('href')
                childObj['cate_title'] = $($(li)[0]).find('a').text()
                obj.child.push(childObj)
            })
        }
        // console.log(obj)
        result.push(obj)
    })
    return result
}

/**
 * @description 获取分类内容
 *
*/
exports.CateHandler = async (req,res) => {
    res.set('Cache-Control','max-age=86400')
    try {
        let {data:_html} = await getHtmlDeatil('/')
        let $ = cheerio.load(_html)
        let cateTitleArr  = getCateTitle($)
        res.send({
            code:200,
            msg:'获取分类列表成功',
            data:{
                cateTitleArr
            }
        })
    } catch (e) {
      res.send({
          code:100,
          msg:e
      })
    }
}
